package com.xjx.service.impl;

import com.cloopen.rest.sdk.BodyType;
import com.cloopen.rest.sdk.CCPRestSmsSDK;
import com.xjx.config.CloopenConfig;
import com.xjx.service.SMSService;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Random;

@Service
public class SMSServiceImpl implements SMSService {

    private static final Logger logger = LoggerFactory.getLogger(SMSServiceImpl.class);

    // ====================== 【重要配置】======================
    // 请将 "1" 替换为您在容联云平台申请的、用于测试的真实模板ID
    private static final String TEST_TEMPLATE_ID = "1";
    // =======================================================


    private final CloopenConfig cloopenConfig;
    private CCPRestSmsSDK sdk;
    private boolean isInitialized = false;

    public SMSServiceImpl(CloopenConfig cloopenConfig) {
        this.cloopenConfig = cloopenConfig;
    }

    @PostConstruct
    public void init() {
        try {
            String restURL = cloopenConfig.getRestURL();
            if (restURL == null || !restURL.matches("https?://.+:.+")) {
                logger.error("容联云短信服务(SMSService)初始化失败！配置项 'rlyun.restURL' 格式不正确。");
                return;
            }
            String serverIp = restURL.split("://")[1].split(":")[0];
            String serverPort = restURL.split("://")[1].split(":")[1];

            sdk = new CCPRestSmsSDK();
            sdk.init(serverIp, serverPort);
            sdk.setAccount(cloopenConfig.getAccountSID(), cloopenConfig.getAuthToken());
            sdk.setAppId(cloopenConfig.getAppID());
            sdk.setBodyType(BodyType.Type_JSON);
            isInitialized = true;
            logger.info("容联云短信服务(SMSService)初始化成功！");
        } catch (Exception e) {
            logger.error("容联云短信服务(SMSService)初始化时发生未知异常！", e);
        }
    }

    @Override
    public boolean sendTestSMS(String to) {
        if (!isInitialized) {
            logger.error("短信服务尚未初始化，无法发送短信。");
            return false;
        }

        // 1. 【已修改】生成一个随机的4位验证码，以满足接口要求
        String randomCode = String.format("%04d", new Random().nextInt(9999));
        // 2. 准备模板需要的数据。假设模板是 {1}代表验证码, {2}代表有效分钟数
        String[] datas = {randomCode, "5"}; // ["随机验证码", "5分钟"]

        logger.info("准备向手机号 [{}] 发送测试短信，模板ID：[{}]，验证码：[{}]", to, TEST_TEMPLATE_ID, randomCode);

        try {
            // 调用SDK的核心方法发送短信
            HashMap<String, Object> result = sdk.sendTemplateSMS(to, TEST_TEMPLATE_ID, datas, null, null);

            if (result == null) {
                logger.error("调用短信SDK后返回null结果。手机号: [{}]", to);
                return false;
            }

            if ("000000".equals(result.get("statusCode"))) {
                logger.info("向手机号 [{}] 发送短信请求成功！响应数据: {}", to, result.get("data"));
                return true;
            } else {
                String errorCode = (String) result.get("statusCode");
                String errorMsg = (String) result.get("statusMsg");
                logger.error("向手机号 [{}] 发送短信请求失败！错误码: [{}], 错误信息: [{}]", to, errorCode, errorMsg);
                return false;
            }
        } catch (Exception e) {
            logger.error("调用短信SDK时发生未知异常！手机号: [{}]", to, e);
            return false;
        }
    }
}